package cn.zxy.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.zxy.model.PageEduInfo;
import cn.zxy.threaLocal.LocalPageInfoUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class PagexAop {

    //定义切点
    @Pointcut("@annotation(cn.zxy.anntation.Pagex)")
    public void point(){}

    //定义环绕方式
    @Around("point()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        String pageNum = ((ServletRequestAttributes) requestAttributes).getRequest().getParameter("pageNum");
        String pageSize = ((ServletRequestAttributes) requestAttributes).getRequest().getParameter("pageSize");

        if(!ObjectUtil.isEmpty(pageNum) && !ObjectUtil.isEmpty(pageSize)){
            PageHelper.startPage(Integer.valueOf(pageNum),Integer.valueOf(pageSize));
        }
        //切点环绕通知
        Object value = joinPoint.proceed();
        //判断value是不是page这个类
        if (value instanceof Page){
            Page page= (Page) value;
            long total = page.getTotal();
            LocalPageInfoUtil.set(PageEduInfo.builder().total(total).build());
        }
        return value;
    }

}
